package org.example.controller;

import org.example.entity.UserInfo;
import org.example.entity.UserLogin;
import org.example.service.LoginService;
import org.example.util.CommonResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author: gx.wu
 * @create: 2023-05-09 15:37
 * @Description:
 */
@RestController
public class LoginController {

    @Resource
    private LoginService loginService;

    @Resource
    private PasswordEncoder passwordEncoder;

//    @PostMapping("/login")
//    public CommonResult<Object> login(String username, String password){
//        UserInfo user = new UserInfo();
//        user.setUserName(username);
//        user.setPassword(password);
//        return login(user);
//    }

    @PostMapping("/user/login")
    public CommonResult<Object> login(@RequestBody UserInfo user){
        CommonResult<Object> result = null;
        try {
            result = loginService.login(user);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.fail(null, "账户或者密码错误！");
        }
        return result;
    }


    @GetMapping("/user/detail")
    public CommonResult<Object> detail(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication == null){
            return CommonResult.fail(null, "用户信息为空");
        }
        UserLogin loginUser = (UserLogin) authentication.getPrincipal();

        return CommonResult.success(loginUser);
    }

    @PostMapping("/test")
    public CommonResult<String> test(String password){
        String encode = passwordEncoder.encode(password);
        System.out.println(encode);
        return CommonResult.success(encode);
    }
}

